package com.niit.springbootshop.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.niit.springbootshop.entity.Categorysecond;
import com.niit.springbootshop.entity.Product;
import com.niit.springbootshop.service.CategorySecondService;
import com.niit.springbootshop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: springboot-demo
 * @description:
 * @author: hanliang
 * @create: 2021-05-11 09:20
 **/
@Controller
public class CategoryController {

    @Autowired
    CategorySecondService categorySecondService;

    @Autowired
    ProductService productService;

    @Value("${page.size}")
    Integer pageSize;

    @RequestMapping("/goCategory")
    public String goCategory(ModelMap map, Integer cid, @RequestParam("csid") String csid, Integer currentPage){
        List<Integer>  ids = new ArrayList<>();

        // 1. 查询二级分类
        List<Categorysecond> csList = categorySecondService.getByCid(cid);
        map.addAttribute("csList",csList);

        // 2. 查询全部商品
        if("null".equals(csid)){
            for(Categorysecond cs : csList){
                ids.add(cs.getCsid());
            }
        }else{
            ids.add(Integer.parseInt(csid));
        }

        // 1 实现分页查询
        PageHelper.startPage(currentPage,pageSize);

        List<Product> productList = productService.getByCsid(ids);

        // 2 封装分页数据
        PageInfo page = new PageInfo(productList);

        map.addAttribute("pageInfo",page);
        map.addAttribute("cid",cid);

        if(!"null".equals(csid)){
            map.addAttribute("csid",csid);
        }
        return "category"; //跳转到category.html
    }
}
